package com.visionvera.retrofitservice.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by dongyukun on 2018/1/3.
 */

public class FileUtils {
    public static byte[] FilePath2byte(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public static byte[] File2byte(File file) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public static final int PHOTO_SIZE_LIMIT = 1024 * 1024; // 1M
    public static final float PHOTO_WIDTH_LIMIT = 720.0f;

    public static byte[] scalePhoto(String path) {
        File file = new File(path);
        if (!file.exists()) return new byte[0];
        BitmapFactory.Options option = new BitmapFactory.Options();
        option.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file.getAbsolutePath(), option);
        int outWidth = option.outWidth;
        int outHeight = option.outHeight;
        option.inJustDecodeBounds = false;
        if (outWidth > PHOTO_WIDTH_LIMIT || outHeight > PHOTO_WIDTH_LIMIT) {
            option.inSampleSize = Math.round(Math.max(outWidth / PHOTO_WIDTH_LIMIT, outHeight / PHOTO_WIDTH_LIMIT) + 0.2f);
        }
        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), option);
        final ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
        byte[] byteArray = stream.toByteArray();
        bitmap.recycle();
        return byteArray;
    }
}
